package com.you.rpc.until;

import com.you.rpc.RpcClient;
import com.you.rpc.entity.RpcAddress;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class AddressUtil {
    static final String LOCALHOST_FINAL = "localhost";
    static final String LOCALHOST_IP = "127.0.0.1";

    /**
     * 将字符串localhost:10001转成RpcAddress
     * 提供一定的地址纠错功能,并统一格式
     * 如
     * 127.0.0.1:10001/xx -> localhost:10001
     */
    public static RpcAddress turnToAddress(String address) {
        int x = address.indexOf(":"), p = address.indexOf("/");
        p = p > x ? p : address.length();
        String host = address.substring(0, x);
        if (host.equalsIgnoreCase(LOCALHOST_IP)) {
            host = LOCALHOST_FINAL;
        }
        int port = Integer.parseInt(address.substring(x + 1, p));
        RpcAddress rpcAddress = new RpcAddress();
        rpcAddress.setHost(host);
        rpcAddress.setPort(port);
        return rpcAddress;
    }

    /**
     * 将SocketAddress转成RpcAddress
     */
    public static RpcAddress turnToAddress(InetSocketAddress address) {
        RpcAddress rpcAddress = new RpcAddress();
        rpcAddress.setHost(address.getHostName());
        rpcAddress.setPort(address.getPort());
        return rpcAddress;
    }

}
